<template>
  <div class="app-container">
    <!-- 搜索表单 -->
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="80px">
      <el-form-item label="考试名称" prop="examName">
        <el-input v-model="queryParams.examName" placeholder="请输入考试名称" clearable style="width: 240px" @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="考试类型" prop="examTypeId">
        <el-select v-model="queryParams.examTypeId" placeholder="请选择考试类型" clearable style="width: 240px">
          <el-option v-for="item in examTypeOptions" :key="item.id" :label="item.name" :value="item.id" />
        </el-select>
      </el-form-item>
      <!--<el-form-item label="难度等级" prop="difficulty">-->
        <!--<el-select v-model="queryParams.difficulty" placeholder="请选择难度等级" clearable style="width: 240px">-->
          <!--<el-option label="初级" value="初级" />-->
          <!--<el-option label="中级" value="中级" />-->
          <!--<el-option label="高级" value="高级" />-->
        <!--</el-select>-->
      <!--</el-form-item>-->
      <!--<el-form-item label="状态" prop="status">-->
        <!--<el-select v-model="queryParams.status" placeholder="请选择状态" clearable style="width: 240px">-->
          <!--<el-option label="启用" value="启用" />-->
          <!--<el-option label="停用" value="停用" />-->
        <!--</el-select>-->
      <!--</el-form-item>-->
      <!--<el-form-item label="创建时间">-->
        <!--<el-date-picker v-model="dateRange" style="width: 240px" value-format="yyyy-MM-dd" type="daterange" range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期"></el-date-picker>-->
      <!--</el-form-item>-->
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 操作按钮 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd" v-hasPermi="['system:exams:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate" v-hasPermi="['system:exams:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete" v-hasPermi="['system:exams:remove']">删除</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 数据表格 -->
    <el-table v-loading="loading" :data="examsList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="考试名称" align="center" prop="examName" :show-overflow-tooltip="true" />
      <el-table-column label="考试类型" align="center" prop="examTypeName" :show-overflow-tooltip="true" />
      <el-table-column label="考试领域" align="center" prop="examLevelName" :show-overflow-tooltip="true" />
      <el-table-column label="考试时长(分钟)" align="center" prop="durationMin" width="120" />
      <el-table-column label="题目数量" align="center" prop="questionNum" width="100" />
      <el-table-column label="总分数" align="center" prop="totalScore" width="100" />
      <el-table-column label="及格分数" align="center" prop="passScore" width="100" />
      <el-table-column label="难度等级" align="center" prop="difficulty" width="100">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.difficulty === '初级'" type="success">初级</el-tag>
          <el-tag v-else-if="scope.row.difficulty === '中级'" type="warning">中级</el-tag>
          <el-tag v-else-if="scope.row.difficulty === '高级'" type="danger">高级</el-tag>
          <span v-else>{{ scope.row.difficulty }}</span>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="status" width="100">
        <template slot-scope="scope">
          <el-switch v-model="scope.row.status" active-value="启用" inactive-value="停用" @change="handleStatusChange(scope.row)"></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="200" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-view" @click="handleDetail(scope.row)">详情</el-button>
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)" v-hasPermi="['system:exams:edit']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)" v-hasPermi="['system:exams:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getList" />

    <!-- 新增/编辑弹窗 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="考试类型" prop="examTypeId">
              <el-select v-model="form.examTypeId" placeholder="请选择考试类型" style="width: 100%">
                <el-option v-for="item in examTypeOptions" :key="item.id" :label="item.name" :value="item.id" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="考试名称" prop="examName">
              <el-input v-model="form.examName" placeholder="请输入考试名称" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="考试领域" prop="levelCode">
              <el-select v-model="form.levelCode" placeholder="请选择考试领域" style="width: 100%">
                <el-option v-for="item in examLevelOptions" :key="item.id" :label="item.name" :value="item.id" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="难度等级" prop="difficulty">
              <el-select v-model="form.difficulty" placeholder="请选择难度等级" style="width: 100%">
                <el-option label="初级" value="初级" />
                <el-option label="中级" value="中级" />
                <el-option label="高级" value="高级" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="考试时长(分钟)" prop="durationMin">
              <el-input-number v-model="form.durationMin" :min="1" :max="9999" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="题目数量" prop="questionNum">
              <el-input-number v-model="form.questionNum" :min="1" :max="9999" style="width: 100%" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="总分数" prop="totalScore">
              <el-input-number v-model="form.totalScore" :min="1" :max="9999" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="及格分数" prop="passScore">
              <el-input-number v-model="form.passScore" :min="1" :max="9999" style="width: 100%" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="描述" prop="description">
              <el-input v-model="form.description" type="textarea" placeholder="请输入描述" :rows="3" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="状态" prop="status">
              <el-radio-group v-model="form.status">
                <el-radio label="启用">启用</el-radio>
                <el-radio label="停用">停用</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 详情弹窗 -->
    <el-dialog title="考试详情" :visible.sync="detailOpen" width="800px" append-to-body>
      <el-descriptions :column="2" border>
        <el-descriptions-item label="考试名称">{{ detailForm.examName }}</el-descriptions-item>
        <el-descriptions-item label="考试类型">{{ detailForm.examTypeName }}</el-descriptions-item>
        <el-descriptions-item label="考试领域">{{ detailForm.levelName || detailForm.levelCode }}</el-descriptions-item>
        <el-descriptions-item label="难度等级">
          <el-tag v-if="detailForm.difficulty === '初级'" type="success">初级</el-tag>
          <el-tag v-else-if="detailForm.difficulty === '中级'" type="warning">中级</el-tag>
          <el-tag v-else-if="detailForm.difficulty === '高级'" type="danger">高级</el-tag>
          <span v-else>{{ detailForm.difficulty }}</span>
        </el-descriptions-item>
        <el-descriptions-item label="考试时长">{{ detailForm.durationMin }} 分钟</el-descriptions-item>
        <el-descriptions-item label="题目数量">{{ detailForm.questionNum }}</el-descriptions-item>
        <el-descriptions-item label="总分数">{{ detailForm.totalScore }}</el-descriptions-item>
        <el-descriptions-item label="及格分数">{{ detailForm.passScore }}</el-descriptions-item>
        <el-descriptions-item label="状态">
          <el-tag v-if="detailForm.status === '启用'" type="success">启用</el-tag>
          <el-tag v-else type="danger">停用</el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="创建时间">{{ parseTime(detailForm.createTime) }}</el-descriptions-item>
        <el-descriptions-item label="更新时间">{{ parseTime(detailForm.updateTime) }}</el-descriptions-item>
        <el-descriptions-item label="描述" :span="2">{{ detailForm.description || '暂无描述' }}</el-descriptions-item>
      </el-descriptions>
      <div slot="footer" class="dialog-footer">
        <el-button @click="detailOpen = false">关 闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listExams, getExams, delExams, addExams, updateExams } from "@/api/system/exams";
import { listExamstype } from "@/api/system/examstype";
import { listExamslevel } from "@/api/system/examslevel";

export default {
  name: "Exams",
  dicts: ['sys_normal_disable'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 考试表格数据
      examsList: [],
      // 考试类型选项
      examTypeOptions: [],
      // 考试领域选项
      examLevelOptions: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 是否显示详情弹出层
      detailOpen: false,
      // 日期范围
      dateRange: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        examName: null,
        examTypeId: null,
        levelCode: null,
        difficulty: null,
        status: null
      },
      // 表单参数
      form: {},
      // 详情表单参数
      detailForm: {},
      // 表单校验
      rules: {
        examTypeId: [
          { required: true, message: "考试类型不能为空", trigger: "change" }
        ],
        examName: [
          { required: true, message: "考试名称不能为空", trigger: "blur" }
        ],
        levelCode: [
          { required: true, message: "考试领域不能为空", trigger: "change" }
        ],
        durationMin: [
          { required: true, message: "考试时长不能为空", trigger: "blur" }
        ],
        questionNum: [
          { required: true, message: "题目数量不能为空", trigger: "blur" }
        ],
        totalScore: [
          { required: true, message: "总分数不能为空", trigger: "blur" }
        ],
        passScore: [
          { required: true, message: "及格分数不能为空", trigger: "blur" }
        ],
        difficulty: [
          { required: true, message: "难度等级不能为空", trigger: "change" }
        ],
        status: [
          { required: true, message: "状态不能为空", trigger: "change" }
        ]
      }
    };
  },
  created() {
    // 先获取考试类型和考试领域选项，再获取考试列表
    Promise.all([
      this.getExamTypeOptions(),
      this.getExamLevelOptions()
    ]).then(() => {
      this.getList();
    }).catch(() => {
      // 即使选项获取失败，也要获取考试列表
      this.getList();
    });
  },
  methods: {
    /** 查询考试列表 */
    getList() {
      this.loading = true;
      listExams(this.addDateRange(this.queryParams, this.dateRange)).then(response => {
        if (response.code === 200) {
          this.examsList = response.rows;
          this.total = response.total;
          // 确保考试类型名称和考试领域名称正确显示
          this.examsList.forEach(exam => {
            if (!exam.examTypeName && exam.examTypeId) {
              exam.examTypeName = this.getExamTypeName(exam.examTypeId);
            }
            if (!exam.levelName && exam.levelCode) {
              exam.levelName = this.getExamLevelName(exam.levelCode);
            }
          });
        } else {
          this.$modal.msgError("获取考试列表失败");
        }
        this.loading = false;
      }).catch(error => {
        console.error("获取考试列表失败:", error);
        this.$modal.msgError("获取考试列表失败");
        this.loading = false;
      });
    },
    /** 查询考试类型选项 */
    getExamTypeOptions() {
      return listExamstype({pageNum:1,pageSize:1000}).then(response => {
        if (response.code === 200) {
          this.examTypeOptions = response.rows || [];
        } else {
          this.$modal.msgError("获取考试类型列表失败");
        }
      }).catch(error => {
        console.error("获取考试类型列表失败:", error);
        this.$modal.msgError("获取考试类型列表失败");
      });
    },
    /** 查询考试领域选项 */
    getExamLevelOptions() {
      return listExamslevel({pageNum:1,pageSize:1000}).then(response => {
        if (response.code === 200) {
          this.examLevelOptions = response.rows || [];
        } else {
          this.$modal.msgError("获取考试领域列表失败");
        }
      }).catch(error => {
        console.error("获取考试领域列表失败:", error);
        this.$modal.msgError("获取考试领域列表失败");
      });
    },
    /** 根据考试类型ID获取考试类型名称 */
    getExamTypeName(examTypeId) {
      if (!examTypeId || !this.examTypeOptions.length) {
        return '';
      }
      const examType = this.examTypeOptions.find(item => item.id == examTypeId);
      return examType ? examType.name : '';
    },
    /** 根据考试领域编码获取考试领域名称 */
    getExamLevelName(levelCode) {
      if (!levelCode || !this.examLevelOptions.length) {
        return '';
      }
      const examLevel = this.examLevelOptions.find(item => item.levelCode == levelCode);
      return examLevel ? examLevel.levelName : '';
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        examTypeId: null,
        levelCode: null,
        examName: null,
        description: null,
        durationMin: null,
        questionNum: null,
        passScore: null,
        totalScore: null,
        difficulty: null,
        status: "启用"
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      // 重置考试类型和考试领域筛选
      this.queryParams.examTypeId = null;
      this.queryParams.levelCode = null;
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加考试";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getExams(id).then(response => {
        if (response.code === 200) {
          this.form = response.data;
          // 确保考试类型和考试领域选项已加载
          if (this.examTypeOptions.length === 0 || this.examLevelOptions.length === 0) {
            Promise.all([
              this.examTypeOptions.length === 0 ? this.getExamTypeOptions() : Promise.resolve(),
              this.examLevelOptions.length === 0 ? this.getExamLevelOptions() : Promise.resolve()
            ]).then(() => {
              // 选项加载完成后，再次设置表单数据
              this.form = response.data;
            });
          }
          this.form.examTypeId = this.form.examTypeId? Number(this.form.examTypeId):''
          this.form.levelCode = this.form.levelCode? Number(this.form.levelCode):''
          this.open = true;
          this.title = "修改考试";
        } else {
          this.$modal.msgError("获取考试信息失败");
        }
      }).catch(error => {
        console.error("获取考试信息失败:", error);
        this.$modal.msgError("获取考试信息失败");
      });
    },
    /** 详情按钮操作 */
    handleDetail(row) {
      this.reset();
      const id = row.id;
      getExams(id).then(response => {
        if (response.code === 200) {
          this.detailForm = response.data;
          // 如果后端没有返回examTypeName，则根据examTypeId获取
          if (!this.detailForm.examTypeName && this.detailForm.examTypeId) {
            this.detailForm.examTypeName = this.getExamTypeName(this.detailForm.examTypeId);
          }
          // 如果后端没有返回levelName，则根据levelCode获取
          if (!this.detailForm.levelName && this.detailForm.levelCode) {
            this.detailForm.levelName = this.getExamLevelName(this.detailForm.levelCode);
          }
          this.detailOpen = true;
        } else {
          this.$modal.msgError("获取考试详情失败");
        }
      }).catch(error => {
        console.error("获取考试详情失败:", error);
        this.$modal.msgError("获取考试详情失败");
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateExams(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addExams(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除考试编号为"' + ids + '"的数据项？').then(function() {
        return delExams(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('exams/export', {
        ...this.queryParams
      }, `exams_${new Date().getTime()}.xlsx`)
    },
    /** 状态修改 */
    handleStatusChange(row) {
      let text = row.status === "启用" ? "启用" : "停用";
      this.$modal.confirm('确认要"' + text + '""' + row.examName + '"考试吗？').then(function() {
        return updateExams(row);
      }).then(() => {
        this.$modal.msgSuccess(text + "成功");
      }).catch(function() {
        row.status = row.status === "启用" ? "停用" : "启用";
      });
    }
  }
};
</script>
